from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from utils.redis import redis_client, close_redis
from utils.database import engine
from sqlalchemy import text
from api import categoriesApi, worksApi
import os


# 读取并执行SQL文件
def execute_sql_file():
    print("表结构初始化")
    sql_file_path = os.path.join(os.path.dirname(__file__), 'sql', 'schema.sql')
    with open(sql_file_path, 'r', encoding='utf-8') as file:
        sql_statements = file.read()
    # 分割SQL语句并执行
    for statement in sql_statements.split(';'):
        statement = statement.strip()
        if statement:
            with engine.connect() as conn:
                conn.execute(text(statement))
                conn.commit()


# fastapi生命周期事件
@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时的初始化
    print("应用启动")
    # execute_sql_file()
    yield
    # 退出时的清理操作
    print("应用关闭")
    await close_redis()


# 配置fastapi实例
app = FastAPI(
    lifespan=lifespan,
    title="文学作品管理系统",
    description="一个用于管理文学作品的后端 API",
    version="1.0.0"
)

# 配置跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 注册路由
app.include_router(categoriesApi.router, prefix="/categories", tags=["categories"])
app.include_router(worksApi.router, prefix="/works", tags=["works"])


# 启动入口
if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='127.0.0.1', port=8000)